// pages/lawhall/index.js
const app = getApp()
const {
  messageset,
  messagetop,
  adtop,
  pay,
  adverfabu,
  adveredit
} = require('../../utils/api')
const {
  fetch,
  newFetch
} = require('../../utils/fetch')

const {
  formatDate
} = require('../../utils/util')
const dateTimePicker = require('../../utils/dateTimePicker.js');
const {
  BASEURL
} = require('../../utils/baseurl')

import {
  Base
} from '../../utils/base.js';
var base = new Base();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    type: '',
    type_id: 0,
    sub_type_id: 0,
    sub_type_info: [],

    // title: '',
    details: '', //描述
    address: '',

    pushName: '',
    pushPhone: '',

    logo_img: [],
    imgs: [],

    sel_start_time: '',
    sel_top_idx: -1,
    topInfo: [],
    cur_mid: 0,

    remark_arr: [],
    region: ['请选择地区', '', ''],
    adverType: 1,


    advertislist: [], //广告logo
    advertisimg: [],
    adverdetailist: [], //广告详情
    adverdetailimg: [],

    merchantslist: [], //商户logo
    merchantsimgs: [],
    merchantdetailist: [], //商户详情
    merchantdetaiimgs: [],

    checked: true,
    checked1: true,
    startimedate: formatDate(new Date()),
    freindex: 0,
    topInfo: Array,
    timeArr: ['七天', '半个月', '一个月', '一季度', '半年', '一年'],
    currentDate: new Date().getTime(),
    show: false,
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      }
      return value
    },

    typeindex: null,
    editval: {}, //编辑
    editid: 0, //编辑id
    ispageEdit: true,
    formId: '',

    isDisable: 0,
    istypetrue: null,
    specificarea: null,
    systemInfo: '',
    isagent: 0,
    pubdisabled:false,
    savedisabled:false,


    show_tip: 0,
    tip: 'init',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (wx.getStorageSync('specificarea')) {
      this.setData({
        specificarea: wx.getStorageSync('specificarea')
      })
    }

    fetch(`wx/message/${this.data.specificarea}/messageset`, 'POST').then(res => {
      this.setData({
        toptimes: res.toptimes
      })
    })

    fetch(`wx/ad/${this.data.specificarea}/adtop`, 'POST').then(res => {
      this.setData({
        topInfo: res
      })
    })

    if (wx.getStorageSync('userInfo')) {
      let userInfo = wx.getStorageSync('userInfo');
      if (userInfo.isagent == null) {
        this.setData({
          isagent: 0
        })
      } else {
        this.setData({
          isagent: userInfo.isagent
        })
      }
      if (this.data.isagent == 0) {
        this.setData({
          pushPhone: userInfo.mobile,
          pushName: userInfo.nickname,
        })
      }
    }


    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    this.setData({
      dateTime1: obj1.dateTime,
      dateTimeArray1: obj1.dateTimeArray
    });

    var sub_type_id = 1;
    this.setData({
      type_id: 0,
      sub_type_id: sub_type_id
    })

    if (options.editid) {
      this.setData({
        editid: options.editid
      })
    } else {
      this.setData({
        istypetrue: 1
      })
    }
    if (options.ediddata) {
      this.setData({
        editval: JSON.parse(options.ediddata),
        ispageEdit: false,
        checked:false
      })
      let {
        editval
      } = this.data;
      var detalogo = editval.img && editval.img.split(",");
      var detailimg
      var detaiimgList = editval.detailimg && editval.detailimg.split(",");
      var editcity = editval.city && editval.city.split(",");
      if (detaiimgList.length > 9) {
        detailimg = detaiimgList.slice(0, 9)
      } else {
        detailimg = detaiimgList
      }

      if (editval.adtypeid == 1) {
        this.setData({
          advertislist: [detalogo], //广告logo
          advertisimg: [detalogo],
          adverdetailist: detailimg, //广告详情
          adverdetailimg: detailimg,
          sub_type_id: editval.adtypeid,
          isDisable: 1,

          details: editval.details,
          pushName: editval.pushName,
          pushPhone: editval.pushPhone,
          address: editval.address,
          region: editcity,

          startimedate: editval.startTime || this.data.startimedate,
          freindex: editval.day == 0 ? 0 : editval.day - 1
        })
        return;
      }
      if (editval.adtypeid == 2) {
        this.setData({
          merchantslist: detalogo, //商户logo
          merchantsimgs: detalogo,
          merchantdetailist: detailimg, //商户详情
          merchantdetaiimgs: detailimg,
          sub_type_id: editval.adtypeid,
          isDisable: 2,

          details: editval.details,
          pushName: editval.pushName,
          pushPhone: editval.pushPhone,
          address: editval.address,
          region: editcity,

          startimedate: editval.startTime || this.data.startimedate,
          freindex: editval.day == 0 ? 0 : editval.day - 1
        })
        return;
      }
    }


    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        if (res.system.indexOf('iOS') == 0) {
          that.setData({
            systemInfo: 'iOS'
          })
        } else {
          that.setData({
            systemInfo: 'Android'
          })
        }
      }
    })

  },
  bind_sub_type: function (e) {
    this.setData({
      "sub_type_id": e.currentTarget.dataset.id
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},

  showToast: function (title) {
    wx.showToast({
      title,
      icon: 'none',
      duration: 1000
    })
  },


  // 输入框的描述值
  goinputdetail: function (e) {
    this.setData({
      details: e.detail.value
    })
  },

  // 输入框的联系人值
  goinputpushName: function (e) {
    this.setData({
      pushName: e.detail.value
    })
  },
  // 输入框的电话值
  goinputpushPhone: function (e) {
    this.setData({
      pushPhone: e.detail.value
    })
  },
  // 输入框地址
  goinputaddress: function (e) {
    this.setData({
      address: e.detail.value
    })
  },

  // 地址选择
  bindRegionChange: function (e) {
    var val_arr = e.detail.value;
    if (val_arr[0] == '全部' && val_arr[1] == '全部' && val_arr[2] == '全部') {
      this.setData({
        region: ['请选择地区']
      })
      return;
    }
    this.setData({
      region: e.detail.value
    })
  },


  // 是否置顶
  onChange(event) {
    this.setData({
      checked: event.detail
    })
  },
  onChange1(event) {
    this.setData({
      checked1: event.detail
    })
  },
  bindPickerChange: function (e) {
    this.setData({
      freindex: e.detail.value
    })
  },
  // onInput(event) {
  // var d = new Date(event.detail);
  // d = formatDate(d);
  // this.setData({
  //     currentDate: event.detail,
  //     startimedate: d
  // })
  // },
  togglePicker() {
    this.setData({
      show: !this.data.show,
    })
  },

  jumpToAgreement() {
    wx.navigateTo({
      url: '/pages/login/agreement'
    })
  },



  // 置顶
  publishFN: function (e) {
    this.data.sel_top_idx = 0;
    this.setData({
      formId: e.detail.formId
    })
    let data = this.data
    var that = this;

    let userInfo = wx.getStorageSync('userInfo');
    if (this.data.sub_type_id == 1) {
      if (data.advertislist.length < 1) {
        this.showToast('请上传广告logo');
        return;
      }
      if (data.adverdetailimg.length < 1) {
        this.showToast('请上传广告详情图');
        return;
      }

      wx.showLoading({
        title: '发布中',
      })
      this.setData({
        pubdisabled:true
       })

      var adeverimg = data.adverdetailimg
      if (data.adverdetailimg > 9) {
        adeverimg = adeverimg.slice(0, 9)
      } else {
        adeverimg = data.adverdetailimg
      }

      var re_param = {
        "area": this.data.specificarea,
        "memberId": userInfo["id"],
        "img": data.advertisimg,
        "detailimg": adeverimg,
        "adtypeid": data.sub_type_id,

        "details": data.details,
        "pushName": data.pushName,
        "pushPhone": data.pushPhone,
        "address": data.address,
        "city": data.region,

        "istop": 0,
        "startTime": '',
        "day": 0,
        "deadline": 0,
        "fee": 0
      };
    } else {
      if (data.merchantslist.length < 1) {
        this.showToast('请上传商户图片');
        return;
      }
      if (data.merchantdetaiimgs.length < 1) {
        this.showToast('请上传商户详情图');
        return;
      }


      var merchtimg = data.merchantdetaiimgs
      if (data.merchantdetaiimgs > 9) {
        merchtimg = merchtimg.slice(0, 9)
      } else {
        merchtimg = data.merchantdetaiimgs
      }

      var re_param = {
        "area": this.data.specificarea,
        "memberId": userInfo["id"],
        "img": data.merchantsimgs,
        "detailimg": merchtimg,
        "adtypeid": data.sub_type_id,

        "details": data.details,
        "pushName": data.pushName,
        "pushPhone": data.pushPhone,
        "address": data.address,
        "city": data.region,

        "istop": 0,
        "startTime": '',
        "day": 0,
        "deadline": 0,
        "fee": 0
      };
    }

    if (this.data.sel_top_idx >= 0) {
      var sel_top_info = this.data.topInfo[this.data.freindex];
      re_param["istop"] = 1;
      re_param["startTime"] = this.data.startimedate;
      re_param["day"] = sel_top_info['day'];
      re_param["deadline"] = this.data.toptimes;
      re_param["fee"] = sel_top_info['curmoney'];
    }

    var jump_url = '/pages/index/index?id=';
    this.data.cbj_url = jump_url;
    if (this.data.istypetrue) {
      fetch(`wx/ad/${this.data.specificarea}/fabu`, 'POST', re_param).then(res => {
        if (res) {
          that.data.cur_mid = res.id;
          if (res.fee > 0) {
            wx.hideLoading()
            if (that.data.systemInfo == 'iOS') {
              wx.showToast({
                title: 'iOS不支持虚拟支付',
                icon: 'none',
                duration: 1500
              })
              return;
            }
            that.pay(res.fee, res.id, res.orderId);
          } else {
            //跳转
            wx.redirectTo({
              url: that.data.cbj_url + that.data.cur_mid,
            })
          }
        }
      })
    }

    //  判断是否是编辑页面
    if (this.data.editval) {
      if (this.data.editid) {
        re_param['id'] = this.data.editid
        this.setData({
          savedisabled:true
        })
        if (this.data.checked) {
          wx.hideLoading()
          if (that.data.systemInfo == 'iOS') {
            wx.showToast({
              title: 'iOS不支持虚拟支付',
              icon: 'none',
              duration: 1500
            })
            return;
          }
          that.payRenew(this.data.editid, re_param)
        }  else {
          newFetch(`wx/ad/${this.data.specificarea}/edit`, 'POST', re_param).then(res=>{
            if(res) {
                wx.hideLoading()
                wx.redirectTo({
                  url: that.data.cbj_url + that.data.cur_mid,
                })
            }
          })
        }

      }
    }
  },
  pay: function (fee, typeId, orderId) {
    var that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let obg = {
      area: this.data.specificarea,
      openId: userInfo['openid'],
      memberId: userInfo['id'],
      // money: '0.01',
      money: this.data.topInfo[this.data.freindex]['curmoney'],
      orderdesc: '小微服务',
      orderId: orderId, // new Date().getTime() + '',
      type: 3,
      typeId: typeId,
      formId: that.data.formId
    }

    fetch(`wx/pay/${this.data.specificarea}/pay`, 'POST', obg).then(info => {

      wx.requestPayment({
        timeStamp: info.timeStamp,
        nonceStr: info.nonceStr,
        package: `prepay_id=${info.prepayId}`,
        signType: 'MD5',
        paySign: info.paySign,
        success: function (res) {
          wx.showToast({
            title: '付款成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(() => {
            wx.redirectTo({
              url: that.data.cbj_url + that.data.cur_mid,
            })

          }, 2000)
        },
        fail: function (res) {
          that.setData({
            pubdisabled:false
          })
          wx.showToast({
            title: '取消付款成功',
            icon: 'success',
            duration: 2000
          })
        }
      })
    })
  },


  payRenew: function (typeId, re_param) {
    var that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let obg = {
      area: this.data.specificarea,
      openId: userInfo['openid'],
      memberId: userInfo['id'],
      // money: '0.01',
      money: this.data.topInfo[this.data.freindex]['curmoney'],
      orderdesc: '小微服务',
      // orderId: orderId,
      type: 1,
      typeId: typeId,
      formId: that.data.formId
      // type就是那个消息1，商户2 广告3 typeid就是对应的id
    }
    fetch(`wx/pay/${this.data.specificarea}/payRenew`, 'POST', obg).then(info => {
      wx.requestPayment({
        timeStamp: info.timeStamp,
        nonceStr: info.nonceStr,
        package: `prepay_id=${info.prepayId}`,
        signType: 'MD5',
        paySign: info.paySign,
        success: function (res) {
          wx.showToast({
            title: '付款成功',
            icon: 'success',
            duration: 2000
          })
          that.saveEdit(info, re_param)
        },
        fail: function (res) {
          that.setData({
            savedisabled: false
          })
          wx.showToast({
            title: '取消付款成功',
            icon: 'success',
            duration: 2000
          })
        }
      })
    })
  },

  saveEdit:function (info, re_param) {
    var that = this;
    if (info.orderCode) {
      newFetch(`wx/pay/${this.data.specificarea}/checkOrderPayStatus`, 'POST', {
        orderId: info.orderCode
      }).then(res => {
        if (res.data.payStatus == 1) {
          re_param['payStatus'] = res.data.payStatus
          re_param['orderCode'] = res.data.orderCode
          newFetch(`wx/ad/${this.data.specificarea}/edit`, 'POST', re_param).then(res=>{
            if(res) {
                wx.hideLoading()
                wx.redirectTo({
                  url: that.data.cbj_url + that.data.cur_mid,
                })
            }
          })
        }
      })
    }
  },




  // 上传广告logo图片
  upload(e) {
    const _this = this
    var imgtype = e.currentTarget.dataset.imgtype;
    var resupimg = []

    let {
      advertislist,
      adverdetailist,
      adverdetailimg
    } = this.data;
    var imgcount = 1;
    if (imgtype == 'detaitype') {
      // imgcount=9-adverdetailist.length
      imgcount = 9 - adverdetailimg.length
    }
    wx.chooseImage({
      count: imgcount,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        var tempFilePaths = res.tempFilePaths;
        for (var i = 0; i < tempFilePaths.length; i++) {
          if (imgtype == 'advertising') {
            advertislist.push(tempFilePaths[i]);
            this.setData({
              advertislist: advertislist,
            })
            wx.uploadFile({
              url: `${BASEURL}wx/upload/image`,
              filePath: res.tempFilePaths[i],
              name: 'image',
              formData: {
                file: advertislist,
                type: 'img'
              },
              success: (res) => {
                if (res.statusCode == 200) {
                  var resdata = JSON.parse(res.data);
                  _this.setData({
                    //   advertisimg:_this.data.advertisimg.concat(resdata.data.url),
                    advertisimg: [resdata.data.url],
                  })
                }
              },
              fail: function (res) {}
            })
          }
        }
        // 广告  九图
        if (imgtype == 'detaitype') { 
          _this.setData({
            tip: '已选图片,正在上传..',
            show_tip: 1,
          })
          res.tempFilePaths.forEach((item,index) => {
            wx.uploadFile({
              url: `${BASEURL}wx/upload/image`,
              filePath: item,
              name: 'image',
              formData: {
                type: 'img'
              },
              success: (res) => {
                var resdata = JSON.parse(res.data);
                if (resdata.code == '200') {
                  resupimg[index] = resdata.data.url
                  this.setData({
                    adverdetailimg: resupimg
                  })
                  _this.setData({
                        tip: '显示',
                        show_tip: 0
                      })
                } else if (resdata.code == '404') {
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'none'
                  })
                }
                },
                fail: function (res) {
                  console.log(res, 'fail')
                }
              })
          })
        }
      }
    })
  },
  previewImage(e) {
    let index = e.target.dataset.index
    let {
      advertislist,
      adverdetailimg,
    } = this.data;
    var imgtype = e.currentTarget.dataset.imgtype;
    if (imgtype == 'advertising') {
      wx.previewImage({
        current: advertislist[index],
        urls: advertislist
      })
    }
    if (imgtype == 'detaitype') {
      wx.previewImage({
        current: adverdetailimg[index],
        urls: adverdetailimg
      })
    }
  },
  remove(e) {
    const _this = this
    let index = e.target.dataset.index
    let {
      advertislist,
      adverdetailist,
      advertisimg,
      adverdetailimg
    } = this.data;
    var imgtype = e.currentTarget.dataset.imgtype;

    if (imgtype == 'advertising') {
      wx.showModal({
        title: '提示',
        content: '您确定要删除本张图片吗？',
        success(res) {
          if (res.confirm) {
            advertislist.splice(index, 1)
            advertisimg.splice(index, 1)
            _this.setData({
              advertislist,
              advertisimg
            })
          } else if (res.cancel) {}
        }
      })
    }
    if (imgtype == 'detaitype') {
      wx.showModal({
        title: '提示',
        content: '您确定要删除本张图片吗？',
        success(res) {
          if (res.confirm) {
            // adverdetailist.splice(index, 1)
            adverdetailimg.splice(index, 1)
            _this.setData({
              // adverdetailist,
              adverdetailimg
            })
          } else if (res.cancel) {}
        }
      })
    }
  },





  // 上传商户logo图片
  merchantsupload(e) {
    const _this = this
    var imgtype = e.currentTarget.dataset.imgtype;
    var resupimg = []

    let {
      merchantslist,
      merchantdetailist,
      merchantdetaiimgs
    } = this.data;
    var imgcount = 1;
    if (imgtype == 'introdudetail') {
      // imgcount = 9 -merchantdetailist.length
      imgcount = 9 - merchantdetaiimgs.length
    }

    wx.chooseImage({
      count: imgcount,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        var tempFilePaths = res.tempFilePaths;
        for (var i = 0; i < tempFilePaths.length; i++) {
          if (imgtype == 'introdutype') {
            merchantslist.push(tempFilePaths[i]);
            this.setData({
              merchantslist: merchantslist,
            })
            wx.uploadFile({
              url: `${BASEURL}wx/upload/image`,
              filePath: res.tempFilePaths[i],
              name: 'image',
              formData: {
                file: merchantslist,
                type: 'img'
              },
              success: (res) => {
                if (res.statusCode == 200) {
                  var resdata = JSON.parse(res.data);
                  _this.setData({
                    //   merchantsimgs:_this.data.merchantsimgs.concat(resdata.data.url),
                    merchantsimgs: [resdata.data.url],
                  })
                }
              },
              fail: function (res) {}
            })
          }
        }
        // 商户广告   九图
        if (imgtype == 'introdudetail') {
          _this.setData({
            tip: '已选图片,正在上传..',
            show_tip: 1,
          })
          res.tempFilePaths.forEach((item,index) => {
            wx.uploadFile({
              url: `${BASEURL}wx/upload/image`,
              filePath: item,
              name: 'image',
              formData: {
                type: 'img'
              },
              success: (res) => {
                var resdata = JSON.parse(res.data);
                if (resdata.code == '200') {
                  resupimg[index] = resdata.data.url
                  this.setData({
                    merchantdetaiimgs: resupimg
                  })
                  _this.setData({
                        tip: '显示',
                        show_tip: 0
                      })
                } else if (resdata.code == '404') {
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'none'
                  })
                }
                },
                fail: function (res) {
                  console.log(res, 'fail')
                }
              })
          })

          // wx.uploadFile({
          //   url: `${BASEURL}wx/upload/image`,
          //   filePath: tempFilePaths[i],
          //   name: 'image',
          //   formData: {
          //     // file: merchantdetailist,
          //     type: 'img'
          //   },
          //   success: (res) => {
          //     if (res.statusCode == 200) {
          //       var resdata = JSON.parse(res.data);
          //       this.setData({
          //         merchantdetaiimgs: _this.data.merchantdetaiimgs.concat(resdata.data.url),
          //       })
          //       _this.setData({
          //         tip: '显示',
          //         show_tip: 0
          //       })
          //     }
          //   },
          //   fail: function (res) {}
          // })
        }
      }
    })
  },
  previewImageimgs(e) {
    let index = e.target.dataset.index
    let {
      merchantslist,
      merchantdetaiimgs,
    } = this.data;
    var imgtype = e.currentTarget.dataset.imgtype;
    if (imgtype == 'introdutype') {
      wx.previewImage({
        current: merchantslist[index],
        urls: merchantslist
      })
    }
    if (imgtype == 'introdudetail') {
      wx.previewImage({
        current: merchantdetaiimgs[index],
        urls: merchantdetaiimgs
      })
    }
  },
  removemerchants(e) {
    const _this = this
    let index = e.target.dataset.index
    let {
      merchantslist,
      merchantdetailist,
      merchantsimgs,
      merchantdetaiimgs
    } = this.data;
    var imgtype = e.currentTarget.dataset.imgtype;

    if (imgtype == 'introdutype') {
      wx.showModal({
        title: '提示',
        content: '您确定要删除本张图片吗？',
        success(res) {
          if (res.confirm) {
            merchantslist.splice(index, 1)
            merchantsimgs.splice(index, 1)
            _this.setData({
              merchantslist,
              merchantsimgs
            })
          } else if (res.cancel) {}
        }
      })
    }
    if (imgtype == 'introdudetail') {
      wx.showModal({
        title: '提示',
        content: '您确定要删除本张图片吗？',
        success(res) {
          if (res.confirm) {
            // merchantdetailist.splice(index, 1)
            merchantdetaiimgs.splice(index, 1)
            _this.setData({
              // merchantdetailist,
              merchantdetaiimgs
            })
          } else if (res.cancel) {}
        }
      })
    }
  },



  changeDateTime1(e) {
    // let month = e.detail.value[1] + 1;
    // let dtime = e.detail.value[2] + 1;
    // let atime = '20' + e.detail.value[0] + '-' + month + '-' + dtime + ' ' + e.detail.value[3] + ':' + e.detail.value[4];
    // this.setData({
    //   startimedate: atime
    // })

    const that=this;
    this.setData({ dateTime1: e.detail.value });
    var aaa1 = that.data.dateTime1[0];
    var aaa2 = that.data.dateTime1[1];
    var aaa3 = that.data.dateTime1[2];
    var aaa4 = that.data.dateTime1[3];
    var aaa5 = that.data.dateTime1[4];
    // var aaa6 = that.data.dateTime[5];
 
    var time1 = that.data.dateTimeArray1[0][aaa1];
    var time2 = that.data.dateTimeArray1[1][aaa2];
    var time3 = that.data.dateTimeArray1[2][aaa3];
    var time4 = that.data.dateTimeArray1[3][aaa4];
    var time5 = that.data.dateTimeArray1[4][aaa5];
    // var time6 = that.data.dateTimeArray[5][aaa6];
    var time = time1 + '-' + time2 + '-' + time3 + ' ' + time4 + ':' + time5;
    this.setData({
      startimedate: time
    })
  },
  changeDateTimeColumn1(e) {
    var arr = this.data.dateTime1,
      dateArr = this.data.dateTimeArray1;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr
    });
  },


})